package com.visionet.school.app.web.web;

import com.visionet.school.app.web.common.utilities.props.PropsKeys;
import com.visionet.school.app.web.common.utilities.props.PropsUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by hxpeng on 2017/3/20.
 */

@Controller
public class UploadController {

    private final static Logger logger = LoggerFactory.getLogger(UploadController.class);

    //下载图片保存的地址
    private static final String SERVER_IMG_PATH = PropsUtil.getProperty(PropsKeys.SERVER_IMG_PATH);

    private static final String SERVER_PATH = PropsUtil.getProperty(PropsKeys.SERVER_PATH);

    private static final String SEPARATOR = "/";

    /**
     * 设置头像
     * @param file
     * @return
     */
    @RequestMapping(value = "/uploadImg", method = RequestMethod.POST)
    public ResponseEntity<?> uploadImg(@RequestParam("picUrl") MultipartFile file){
        Map<String,Object> map = new HashMap<>();
        try {
            String fileName = file.getOriginalFilename();
            File targetFile = new File(SERVER_IMG_PATH, fileName);
            file.transferTo(targetFile);
            String fileUrl = SERVER_PATH + SEPARATOR + fileName;
            map.put("stat", "success");
            map.put("path",fileUrl);
        } catch (Exception e) {
            logger.error("上传图片失败," + e.getMessage());
            map.put("stat","err");
        }
        return new ResponseEntity(map , HttpStatus.OK);
    }


}
